package bb.lanxing.fragment.sport;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

import bb.lanxing.R;
import bb.lanxing.activity.sport.SportRecordDetailActivity;
import bb.lanxing.adapter.sport.SportRecordListAdapter;
import bb.lanxing.fragment.base.BaseFragment;
import bb.lanxing.model.database.Workout;

public class SportRecordListFragment extends BaseFragment {
    public static final int REQUEST_CODE_DETAIL = 2666;

    private RecyclerView mRecyclerView;
    private SportRecordListAdapter mAdapter;
    private List<Workout> workoutList;

    public SportRecordListFragment() {
    }

    public SportRecordListFragment(List<Workout> workouts) {
        workoutList = workouts;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_sport_record_list, container, false);

        mRecyclerView = view.findViewById(R.id.recyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter = new SportRecordListAdapter(workoutList);
        mAdapter.setOnItemClickListener(position -> {
            Workout workout = workoutList.get(position);
            if (workout != null) {
                Intent intent = new Intent(getActivity(), SportRecordDetailActivity.class);
                intent.putExtra("position", position);
                intent.putExtra("workoutServerId", workout.getServerId());
                startActivityForResult(intent, REQUEST_CODE_DETAIL);
            }
        });
        mRecyclerView.setAdapter(mAdapter);
        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK && requestCode == REQUEST_CODE_DETAIL) {
            int position = data.getIntExtra("position", -1);
            workoutList.remove(position);
            mAdapter.updateData(workoutList);
        }
    }
}